<template>
    <div className="app-container" class="left-bar">
        <!-- 提示信息 -->
        <div v-if="!currentUserId" className="loading-text">
            正在加载用户信息，请稍候...
        </div>

        <!-- 饼状图 -->
        <div v-else ref="pieChart" style="width: 100%; height: 400px; margin-top: 20px;"></div>
    </div>
    <div class="ranking-table" >
        <h3>歌手排名</h3>
        <h5>（点击可查看该歌手更多歌曲）</h5>
        <table>
            <thead>
            <tr>
                <th>排名</th>
                <th @click="sortSingers">歌手名称</th>
                <th>热度</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(singer, index) in topSingers" :key="singer.artistId" @click="goToSingerDetail(singer.artistId)">
                <td>{{ index + 1 }}</td>
                <td>{{ singer.artistName }}</td>
                <td>{{ singer.totalPlayratio.toFixed(2) }}</td>
            </tr>
            </tbody>
        </table>
    </div>
</template>

<script setup name="UserTopSingersChart">
import {ref, computed, onMounted} from "vue";
import * as echarts from "echarts";
import useUserStore from "@/store/modules/user";
import {getUsersTopSingers} from "@/api/UsersTopSingers/UsersTopSingers";

const router = useRouter();
const userStore = useUserStore();
const topSingers = ref([]);
const currentUserId = computed(() => userStore.id); // 动态获取用户ID
const pieChart = ref(null);
import { useRouter } from "vue-router";

// 获取当前用户的Top歌手并绘制饼状图
function fetchTopSingers() {
    if (!currentUserId.value) {
        console.error("用户ID为空，无法获取Top歌手");
        return;
    }

    // 使用 getUsersTopSingers 方法获取数据
    getUsersTopSingers(currentUserId.value).then(response => {
        topSingers.value = response.data.map(item => ({
            artistName: decodeURIComponent(item.artistName.replace(/\+/g, ' ').replace("_", "——")),
            artistId: item.artistId,
            totalPlayratio: item.totalPlayratio
        }));
        if (topSingers.length === 0) {
            console.warn("未找到该用户的Top歌手");
            return;
        }

        // 初始化饼状图
        initChart(topSingers);
    }).catch((error) => {
        console.error("获取Top歌手失败:", error);
    });
}

// 初始化饼状图
function initChart(topSingers) {
    const chartDom = pieChart.value;
    const myChart = echarts.init(chartDom);
    const option = {
        tooltip: {
            trigger: "item",
            formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        series: [
            {
                name: "Top 歌手",
                type: "pie",
                radius: "50%",
                data: topSingers.value.map((singer) => ({
                    value: singer.totalPlayratio, // 假设返回数据中有 totalPlayratio 字段
                    name: singer.artistName, // 假设返回数据中有 artistId 字段
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: "rgba(0, 0, 0, 0.5)",
                    },
                },
            },
        ],
    };
    myChart.setOption(option);
}

// 页面加载时自动获取Top歌手
onMounted(() => {
    fetchTopSingers();
});

function goToSingerDetail(singerId) {
    router.push({ path: `/person-detail/${singerId}` });
}
</script>

<style scoped>
.app-container {
    max-width: 600px;
    margin: 0 auto;
    padding: 0px;
}

.loading-text {
    text-align: center;
    font-size: 16px;
    color: #666;
}
.left-bar {
    float: left;
    width: 50%;
//position: absolute;
//overflow: auto;
}
.right-bar {
    float: right;
    right: 0px;
    width: 40%;
//position: absolute;
//overflow: auto;
}

.ranking-table {
    margin-left: 20px;
    float: right;
    right: 0px;
    width: 40%;
    font-size: large;
    cursor: pointer;
}

.ranking-table h3 {
    margin-bottom: 10px;
}

.ranking-table table {
    width: 100%;
    border-collapse: collapse;
}

.ranking-table th,
.ranking-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.ranking-table th {
    background-color: #f2f2f2;
}
.ranking-table tr:hover {
    background-color: #f5f5f5; /* 鼠标悬停时的背景色 */
}
</style>